const express = require(`express`)
const router = express.Router();
var async = require('async');
const friend = require('../model/friend')
const chat = require('../model/chat') 
router.post('/api/v1/sendMessage', async (req, res) => {
    try {
        var user_id = req.body.user_id
        var friend_id = req.body.friend_id 
        var liaoTianContent = req.body.liaoTianContent 
        var chat_content_time = req.body.chat_content_time
        let findfriend = await friend.findOne({
            "user_id":friend_id,
            "friend_id":user_id
        })
        if(findfriend == null){
          var addfriend = await friend.create({ 
                "user_id":friend_id,
                "friend_id":user_id
                })
        }else{
             console.log("已经添加该好友，无需再添加")
        }

        //

        let findfriendOne = await friend.findOne({
            "user_id":user_id,
            "friend_id":friend_id
        })
        if(findfriendOne == null){
            var addfriendOne = await friend.create({ 
                  "user_id":user_id,
                  "friend_id":friend_id
                  })
          }else{
               console.log("已经添加该好友，无需再添加One")
          }


          //
        let woFaDeXiaoXi = await chat.create({
            "user_id":user_id,
            "friend_id":friend_id,
            "issend":user_id,
            "chat_content":liaoTianContent,
            "chat_content_time":chat_content_time
        })
        let taShouDeXiaoXi = await chat.create({
            "user_id":friend_id,
            "friend_id":user_id,
            "issend":user_id,
            "chat_content":liaoTianContent,
            "chat_content_time":chat_content_time
        })
        let updateme = await friend.update({
            "user_id":user_id,
            "friend_id":friend_id,
        },{$set:{
            latest_information:liaoTianContent,
            latest_information_time:chat_content_time
        }})
        let updatefriend = await friend.update({
            "user_id":friend_id,
            "friend_id":user_id
        },{$set:{
            latest_information:liaoTianContent,
            latest_information_time:chat_content_time
        },$inc: { Unread_number: 1 }})
        if(woFaDeXiaoXi !=null && taShouDeXiaoXi!=null  && updateme !=null&& updatefriend !=null ){
        res.json({
            code: 200,
            message: "发送成功"
        });
        }else{
        res.json({
            code: 200,
            message: "发送失败"
        }); 
        }
        
    } catch (error) {
        console.log(error)
        res.json({
            code: 500,
            message: error
        });
    }
})
module.exports = router